<script lang="ts" setup>
import useModal from '@/hooks/useModal'
import SelectUploadList from './SelectUploadList.vue'
import draggable from 'vuedraggable'

const props = withDefaults(defineProps<{ list: string; limit?: number; disabled?: boolean }>(), {
  limit: 1,
  disabled: false,
})
const emit = defineEmits(['update:show', 'reset', 'confirm', 'update:value'])
const { store } = useModal()
const _list = ref<string[]>(props.list.split(',').filter(Boolean))
watch(
  () => props.list,
  () => {
    _list.value = props.list.split(',').filter(Boolean)
  }
)
const handleRemove = index => {
  if (props.disabled) return
  const list = props.list.split(',')
  list.splice(index, 1)
  emit('update:value', list.join(','))
}
const onConfirm = (imgs: string[]) => {
  let list = props.list.split(',').filter(Boolean)
  list = list.concat(imgs)
  if (list.length > props.limit) {
    list.splice(props.limit)
  }
  emit('update:value', list.join(','))
}
const onClick = () => {
  if (props.disabled) return
  store.handleShow({})
}
const onMove = () => {
  emit('update:value', _list.value.join(','))
}
</script>
<template>
  <div>
    <div class="upload-container flex-w" :class="{ disabled: $props.disabled }">
      <draggable class="imgs flex" :list="_list" @end="onMove" animation="300" ghost-class="ghost" :force-fallback="true" :group="{ name: 'list', pull: 'clone', put: false }" itemKey="name">
        <template #item="{ element, index }">
          <div class="item">
            <div class="icon" @click="handleRemove(index)">
              <icon-close-circle-fill size="20" />
            </div>
            <a-image :src="element" width="50" height="50" />
          </div>
        </template>
      </draggable>

      <div class="upload flex" @click="onClick" v-if="_list.length != props.limit">
        <icon-plus style="margin: auto" />
      </div>
    </div>
    <SelectUploadList v-if="store.show" v-model:show="store.show" @confirm="onConfirm" :limit="props.limit" />
  </div>
</template>
<style lang="less" scoped>
.upload-container {
  cursor: pointer;

  &.disabled {
    cursor: not-allowed;
  }
  .item {
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    .icon {
      position: absolute;
      background: white;
      border-radius: 50%;
      top: -5px;
      right: -5px;
      width: 21px;
      height: 21px;
      z-index: 233;
    }
  }
  .upload {
    width: 50px;
    height: 50px;
    border-radius: 5px;
    background: rgba(0, 0, 0, 0.02);
    border: 1px dotted rgba(0, 0, 0, 0.1);
  }
}
</style>
